package com.flyme.module.base.provider.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.flyme.common.core.utils.ApiAssert;
import com.flyme.common.core.utils.JsonUtils;
import com.flyme.core.base.supper.service.impl.BaseServiceImpl;
import com.flyme.module.base.client.entity.SysVipType;
import com.flyme.module.base.client.entity.SysVipconfig;
import com.flyme.module.base.provider.mapper.SysVipTypeMapper;
import com.flyme.module.base.provider.service.SysVipTypeService;
import com.flyme.module.base.provider.service.SysVipconfigService;
import com.flyme.module.exam.client.vo.ExamItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: zyf
 * @date: 2018/10/24 16:33
 * @description:
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysVipTypeServiceImpl extends BaseServiceImpl<SysVipTypeMapper, SysVipType> implements SysVipTypeService {

    @Autowired
    private SysVipconfigService vipconfigService;

    @Override
    public Boolean add(SysVipType vipType) {
        save(vipType);
        List<SysVipconfig> list = getVipConfigList(vipType);
        return vipconfigService.saveBatch(list);
    }

    private List<SysVipconfig> getVipConfigList(SysVipType vipType) {
        List<ExamItem> examItems = JsonUtils.toList(vipType.getVipConfigItems(), ExamItem.class);
        List<SysVipconfig> list = new ArrayList<>();
        for (ExamItem examItem : examItems) {
            SysVipconfig vipconfig = new SysVipconfig();
            vipconfig.setVipPriItem(examItem.getValue());
            vipconfig.setVipTypeId(vipType.getId());
            list.add(vipconfig);
        }
        return list;
    }

    @Override
    public Boolean update(SysVipType vipType) {
        vipconfigService.deleteByVipTypeId(vipType.getId());
        List<SysVipconfig> list = getVipConfigList(vipType);
        vipconfigService.saveBatch(list);
        return updateById(vipType);
    }


    @Override
    public Boolean delByIds(String[] ids) {
        ApiAssert.notNull("参数不能为空", ids);
        return removeByIds(CollectionUtil.toList(ids));
    }

    /**
     * 查询所有vip
     */
    public List<Map<String, Object>> selectAllVip() {
        return listMaps(q());
    }

    /**
     * 根据code查询vip
     */
    public SysVipType findByCode(String code){
        return getOne(q().eq(true, "vipCode", code), false);
    }
}
